﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.QixingManage;
using YiSha.Model.Param.QixingManage;
using System.Reflection.Metadata;
using NPOI.SS.Formula.PTG;
using YiSha.Web.Code;

namespace YiSha.Service.QixingManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2024-12-28 15:27
    /// 描 述：服务类
    /// </summary>
    public class KnowledgePostsService : RepositoryFactory
    {
        private KnowledgePostMediaService knowledgePostsService = new KnowledgePostMediaService();


        #region 获取数据
        public async Task<List<KnowledgePostsDto>> GetList(KnowledgePostsListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            List<KnowledgePostsDto> knowledgePosts = new List<KnowledgePostsDto>();
            knowledgePosts = list.Select(x => new KnowledgePostsDto
            {

                Id = x.Id.ToString(),
                title = x.title,
                user_id = x.user_id.ToString(),
                content = x.content,
                cover_image = x.cover_image,
                state = x.state,
                knowledgePostMedia = knowledgePostsService.GetList(x.Id).Result,
            }).ToList();
            return knowledgePosts;
        }

        public async Task<List<KnowledgePostsDto>> GetPageList(KnowledgePostsListParam param, Pagination pagination)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression, pagination);
            List<KnowledgePostsDto> knowledgePosts = new List<KnowledgePostsDto>();
            knowledgePosts = list.Select(x => new KnowledgePostsDto
            {

                Id = x.Id.ToString(),
                title = x.title,
                user_id = x.user_id.ToString(),
                content = x.content,
                cover_image = x.cover_image,
                state = x.state,
                knowledgePostMedia = knowledgePostsService.GetList(x.Id).Result,
            }).ToList();
            return knowledgePosts;
        }

        public async Task<KnowledgePostsDto> GetEntity(long id)
        {
            var data = await this.BaseRepository().FindEntity<KnowledgePostsEntity>(id);
            KnowledgePostsDto postsDto = new KnowledgePostsDto();
            postsDto.state = data.state;
            postsDto.title = data.title;
            postsDto.Id = data.Id.ToString();
            postsDto.user_id = data.user_id.ToString();
            postsDto.content = data.content;
            postsDto.cover_image = data.cover_image;
            postsDto.knowledgePostMedia = knowledgePostsService.GetList(data.Id).Result;

            return postsDto;
        }
        #endregion

        #region 提交数据
        public async Task SaveForm(KnowledgePostsDto dto)
        {
            if ( dto.Id == "0")
            {
                //OperatorInfo operatorInfo = await Operator.Instance.Current();

                KnowledgePostsEntity entity = new KnowledgePostsEntity();
                entity.state = dto.state;
                entity.title = dto.title;
                entity.state = dto.state;
                entity.title = dto.title;
                entity.content = dto.content;
                long.TryParse(dto.user_id, out long UserId);
                entity.user_id = UserId;

                entity.view_count = 0;
                entity.cover_image = dto.cover_image;
                entity.created_at = DateTime.UtcNow;
                entity.updated_at = DateTime.UtcNow;
                entity.Create();
                await this.BaseRepository().Insert(entity);

                List<KnowledgePostMediaEntity> knowledgePostMedia = new List<KnowledgePostMediaEntity>();
                 
                for (int i = 0; i < dto.knowledgePostMedia.Count; i++)
                { 
                    dto.knowledgePostMedia[i].post_id = entity.Id;
                    dto.knowledgePostMedia[i].Create();
                    knowledgePostMedia.Add(dto.knowledgePostMedia[i]);
                }

                await knowledgePostsService.SaveForm(knowledgePostMedia);
            }
            else
            {
                KnowledgePostsEntity entity = new KnowledgePostsEntity();
                long.TryParse(dto.Id, out long Id);
                entity.Id = Id;
                entity.state = dto.state;
                entity.title = dto.title;
                entity.state = dto.state;
                entity.title = dto.title;
                entity.content = dto.content;
                entity.view_count = 0;
                entity.cover_image = dto.cover_image;
                entity.updated_at = DateTime.UtcNow;
                await this.BaseRepository().Update(entity);
                
                var list = await knowledgePostsService.GetList(entity.Id); 
                string ids = string.Join(",", list.Select(x => x.Id).ToList());
                var bos = knowledgePostsService.DeleteForm(ids);


                List<KnowledgePostMediaEntity> knowledgePostMedia = new List<KnowledgePostMediaEntity>();

                for (int i = 0; i < dto.knowledgePostMedia.Count; i++)
                {
                    dto.knowledgePostMedia[i].post_id = Id;
                    dto.knowledgePostMedia[i].Create();
                    knowledgePostMedia.Add(dto.knowledgePostMedia[i]);
                }

                 await knowledgePostsService.SaveForm(knowledgePostMedia);

            }
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<KnowledgePostsEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<KnowledgePostsEntity, bool>> ListFilter(KnowledgePostsListParam param)
        {
            var expression = LinqExtensions.True<KnowledgePostsEntity>();
            if (param != null)
            {
                if (!string.IsNullOrEmpty(param.title))
                {
                    expression = expression.And(t => t.title.Contains(param.title));
                }
                //if (!param.tenant_id.IsNullOrZero())
                //{
                //    expression = expression.And(t => t.tenant_id == param.tenant_id);
                //}
            }
            return expression;
        }
        #endregion
    }
}
